use std::sync::{Mutex, Once, Arc};
use tauri::{AppHandle, Wry};
use tauri::tray::TrayIcon;

pub struct AppHandleManager {
    inner: Mutex<Option<AppHandle<Wry>>>,
    tray: Mutex<Option<Arc<TrayIcon<Wry>>>>, // 新增字段
    init: Once,
}

impl AppHandleManager {
    pub fn global() -> &'static Self {
        static INSTANCE: AppHandleManager = AppHandleManager {
            inner: Mutex::new(None),
            tray: Mutex::new(None), // 新增初始化
            init: Once::new(),
        };
        &INSTANCE
    }

    pub fn init(&self, handle: AppHandle<Wry>) {
        self.init.call_once(|| {
            let mut app_handle = self.inner.lock().unwrap();
            *app_handle = Some(handle);
        });
    }

    pub fn get(&self) -> Option<AppHandle<Wry>> {
        self.inner.lock().unwrap().clone()
    }

    pub fn get_handle(&self) -> AppHandle<Wry> {
        self.get().expect("AppHandle not inited")
    }

    pub fn set_tray(&self, tray: TrayIcon<Wry>) {
        let mut tray_lock = self.tray.lock().unwrap();
        *tray_lock = Some(Arc::new(tray));
    }

    pub fn get_tray(&self) -> Option<Arc<TrayIcon<Wry>>> {
        self.tray.lock().unwrap().clone()
    }
}
